package com.gxks.lhs.controller.admin;

import com.gxks.lhs.DTO.LoginDTO;
import com.gxks.lhs.constants.R;
import com.gxks.lhs.security.JwtTokenProvider;
import com.gxks.lhs.security.SecurityUtils;
import com.gxks.lhs.service.IUserService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(tags = "登录模块")
@Slf4j
@RestController
@RequestMapping("/restful-api")
public class LoginController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IUserService userService;

    @Autowired
    private JwtTokenProvider jwtTokenProvider;
    @Autowired
    private AuthenticationManager authenticationManager;


    @PostMapping("/login")
    public R Login(@RequestBody LoginDTO loginRequest) {
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        loginRequest.getUsername(),
                        loginRequest.getPassword()
                )
        );
        log.info("Login: " + authentication.getName());
        String accessToken = jwtTokenProvider.generateAccessToken(authentication.getName(), authentication.getAuthorities().toString());
        String refreshToken = jwtTokenProvider.generateRefreshToken(authentication.getName(), authentication.getAuthorities().toString());
        Map token = new HashMap<String, String>();
        token.put("accessToken", accessToken);
        token.put("refreshToken", refreshToken);
        token.put("user", authentication.getName());
        return R.success(token).add("accessToken", accessToken).add("refreshToken", refreshToken);
    }

    @GetMapping("/refresh")
    public R refresh(@RequestParam String refreshToken) {
        // 检查刷新令牌的有效性
        log.info("用户的refreshToken: " + refreshToken);
        jwtTokenProvider.validateRefreshToken(refreshToken);
        if (!jwtTokenProvider.validateRefreshToken(refreshToken)) {
            return R.error("无效的refreshToken");
        }
        // 从刷新令牌中获取用户信息
        final String username = jwtTokenProvider.getUserIdFromToken(refreshToken);
        final String roles = jwtTokenProvider.getRolesFromToken(refreshToken);
        if (username == null || roles == null) {
            return R.error("无效的refreshToken");
        }
        log.info("用户的username: " + username);
        log.info("用户的roles: " + roles);
        System.out.println("[ROLE_USER]".equals(roles));
        if ("[ROLE_USER]".equals(roles)) {
            if (userService.IsBan(username)) {
                return R.error("该手机号已被封禁");
            }
        }
        // 生成新的访问令牌
        final String newAccessToken = jwtTokenProvider.generateAccessToken(username, roles);
        final String newRefreshToken = jwtTokenProvider.generateRefreshToken(username, roles);
        // 返回新的访问令牌给客户端
        return R.success().add("accessToken", newAccessToken).add("refreshToken", newRefreshToken);
    }

    //    退出登录
    @PostMapping("/logout")
    public R logout() {
        String userId = SecurityUtils.getCurrentUserId();
        SecurityContext context = SecurityContextHolder.getContext();
        context.setAuthentication(null);
        stringRedisTemplate.delete("access_token:" + userId);
        stringRedisTemplate.delete("refresh_token:" + userId);
        return R.success();
    }

    //    获取短信验证码
    @GetMapping("/getCode")
    public R getCode(@RequestParam String phone) {
        if (userService.isExist(phone)) {
            return R.error("该手机号已注册");
        }
//        生成6位随机数字
        String code = String.valueOf((int) (Math.random() * 900000 + 100000));
        return R.success(code);
    }
}
